<?php

namespace common\models\cms;

use Yii;

/**
 * This is the model class for table "{{%cms_article_like}}".
 *
 * @property int $id
 * @property int $article_id 文章ID
 * @property int $comment_id 评论ID
 * @property int $user_id 用户ID
 * @property int $created_at 创建时间
 * @property int $updated_at 更新时间
 */
class CmsArticleLike extends \common\db\ActiveRecord {

    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return '{{%cms_article_like}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['article_id', 'comment_id', 'user_id', 'created_at', 'updated_at'], 'integer'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'article_id' => '文章ID',
            'comment_id' => '评论ID',
            'user_id' => '用户ID',
            'created_at' => '创建时间',
            'updated_at' => '更新时间',
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function afterDelete() {
        parent::afterDelete();
        if ($this->comment_id) {
            $comment = CmsArticleComment::findOne($this->comment_id);
            if ($comment && $comment->likes > 0) {
                $comment->likes -= 1;
                $comment->save();
            }
        } elseif ($this->article_id) {
            $stats = CmsArticleStats::findOrNew([
                'article_id' => $this->article_id,
            ]);
            if (!$stats->isNewRecord) {
                $stats->likes -= 1;
                $stats->save();
            }
        }
    }

    /**
     * {@inheritdoc}
     */
    public function afterSave($insert, $changedAttributes) {
        parent::afterSave($insert, $changedAttributes);
        if ($this->comment_id) {
            $comment = CmsArticleComment::findOne($this->comment_id);
            if ($comment) {
                $comment->likes += 1;
                $comment->save();
            }
        } elseif ($this->article_id) {
            $stats = CmsArticleStats::findOrNew([
                'article_id' => $this->article_id,
            ]);
            if ($stats->isNewRecord) {
                $stats->likes = 1;
            } else {
                $stats->likes += 1;
            }
            $stats->save();
        }
        \common\logics\RewardLogic::praise();
    }

}
